package com.itheima.filter;

import com.itheima.util.CurrentHolder;
import com.itheima.util.JwtUtils;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.http.HttpStatus;
import org.springframework.util.ObjectUtils;

import java.io.IOException;
import java.util.Map;

/***
 * 过滤器
 */

//@Order(8)
//@Component
@WebFilter(urlPatterns = "/*")
public class TokenFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        // 判断当前是否访问登录接口 /login
        String url = request.getRequestURL().toString();
        if (url.contains("/login")) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        //判断当前用户的jwt令牌是否为空 且 正确有效
        String token = request.getHeader("token");
        if (ObjectUtils.isEmpty(token) || JwtUtils.parseJwt(token) == null) {
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            return;
        }
        //有效 -> 将此jwt令牌存入ThreadLocal县城变量中
        Map<String, Object> map = JwtUtils.parseJwt(token);
        CurrentHolder.setCurrentId(Integer.parseInt(map.get("id").toString()));
        filterChain.doFilter(servletRequest, servletResponse);
        CurrentHolder.remove();
    }
}
